import java.util.LinkedList;
import java.util.Queue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 17655
 * Date: 2025-02-26
 * Time: 11:44
 */
public class test1 {
    /**
     * LeetCode 130  被围绕的区域
     */


    int[] dx = {0,0,1,-1};
    int[] dy = {1,-1,0,0};
    int m,n;


    public void solve(char[][] board) {
        m = board.length;
        n = board[0].length;

        // 先处理边界的‘O’
        for(int j=0;j<n;j++){
            if(board[0][j]=='O'){
                bfs(board,0,j);
            }
            if(board[m-1][j]=='O'){
                bfs(board,m-1,j);
            }
        }
        for(int i=0;i<m;i++){
            if(board[i][0]=='O'){
                bfs(board,i,0);
            }
            if(board[i][n-1]=='O'){
                bfs(board,i,n-1);
            }
        }

        // 还原内部的‘O’
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if(board[i][j]=='O'){
                    board[i][j]='X';
                }else if(board[i][j]=='.'){
                    board[i][j]='O';
                }
            }
        }
    }


    public void bfs(char[][] board,int i,int j){
        Queue<int[]> q = new LinkedList<>();
        q.add(new int[]{i,j});
        board[i][j]='.';
        while(!q.isEmpty()){
            int[] t = q.poll();
            int a = t[0];
            int b = t[1];
            for(int k=0;k<4;k++){
                int x = a+dx[k];
                int y = b+dy[k];
                if(x>=0 && x<m && y>=0 && y<n && board[x][y]=='O'){
                    board[x][y] = '.';
                    q.add(new int[]{x,y});
                }
            }
        }
    }
}
